package server;

import loader.WebappLoader;
import mapper.MappedContext;
import mapper.MappedHost;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,MappedHost> hostMap ;

    public RequestProcessor(Socket socket,Map<String, MappedHost> hostMap ) {
        this.socket = socket;
        this.hostMap = hostMap;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());


            //socket.getInetAddress()

            String context = request.getUrl().split("/")[1];
            String url = request.getUrl().replaceAll("/"+context,"");
            MappedContext mappedContext = hostMap.get(request.getHost()).getContextMap().get(context);
            Map<String, HttpServlet> servletMap =  mappedContext.getMappedWrapperMap().getServletMap();
            // 静态资源处理
            if(servletMap.get(url) == null) {
                response.outputHtml(url);
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(url);
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }

}
